<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @click="goBack">
        <text class="nav-icon">←</text>
      </view>
      <view class="nav-title">AI智能助手</view>
      <view class="nav-right"></view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view class="chat-messages" scroll-y :scroll-top="scrollTop" scroll-with-animation>
      <view class="message-list">
        <!-- 欢迎消息 -->
        <view class="message-item assistant">
          <view class="avatar">🤖</view>
          <view class="message-bubble">
            <text class="message-text">您好！我是云诊康AI智能助手，有什么可以帮助您的吗？</text>
          </view>
        </view>

        <!-- 聊天消息列表 -->
        <view v-for="(msg, index) in messages" :key="index" class="message-item" :class="msg.type">
          <view class="avatar" v-if="msg.type === 'assistant'">🤖</view>
          <view class="message-bubble">
            <text class="message-text">{{ msg.content }}</text>
          </view>
          <view class="avatar" v-if="msg.type === 'user'">👤</view>
        </view>

        <!-- AI正在输入提示 -->
        <view v-if="aiTyping" class="message-item assistant">
          <view class="avatar">🤖</view>
          <view class="message-bubble typing">
            <text class="typing-text">AI正在思考中...</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-container">
        <input 
          v-model="inputText" 
          class="message-input" 
          placeholder="请输入您的问题..." 
          :disabled="aiTyping"
          @confirm="sendMessage"
        />
        <button 
          class="send-btn" 
          :class="{ disabled: !inputText.trim() || aiTyping }" 
          @click="sendMessage"
        >
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { chatSymptom } from '@/api/ai'

export default {
  data() {
    return {
      inputText: '',
      messages: [],
      aiTyping: false,
      scrollTop: 0
    }
  },
  onLoad() {
    console.log('进入AI对话页面')
    uni.showToast({ title: 'AI助手已准备就绪', icon: 'none', duration: 1000 })
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 发送消息
    async sendMessage() {
      const text = this.inputText.trim()
      if (!text || this.aiTyping) return

      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: text
      })
      
      // 清空输入框
      this.inputText = ''
      
      // 滚动到底部
      this.scrollToBottom()

      // 开始AI回复
      this.aiTyping = true
      
      try {
        // 调用症状检查API，传递包含memoryId和userMessage的对象
        const response = await chatSymptom(text)
        let aiReply = typeof response === 'string' ? response : (response?.data || 'AI暂时无法回复，请稍后再试')
        
        // 替换AI回复中的固定姓名为当前用户姓名
        aiReply = this.replaceUserName(aiReply)
        
        // 添加AI回复
        this.messages.push({
          type: 'assistant',
          content: aiReply
        })
      } catch (error) {
        console.error('AI对话错误:', error)
        this.messages.push({
          type: 'assistant',
          content: '抱歉，AI助手暂时无法回复，请稍后再试。'
        })
      } finally {
        this.aiTyping = false
        this.scrollToBottom()
      }
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 99999
      })
    },

    // 替换AI回复中的固定姓名为当前用户姓名
    replaceUserName(aiReply) {
      try {
        // 获取当前用户姓名
        const userName = this.$store.getters.name || '用户'
        
        // 替换常见的固定姓名模式
        let processedReply = aiReply
        
        // 替换 "赵云飞先生" 为 "用户名先生/女士"
        processedReply = processedReply.replace(/赵云飞先生/g, `${userName}`)
        
        // 替换其他可能的固定姓名模式
        processedReply = processedReply.replace(/赵云飞/g, userName)
        
        return processedReply
      } catch (error) {
        console.error('替换用户姓名时出错:', error)
        return aiReply
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 32rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e5e5e5;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.nav-left {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-icon {
  font-size: 36rpx;
  color: #333;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.nav-right {
  width: 80rpx;
}

/* 聊天消息区域 */
.chat-messages {
  flex: 1;
  margin-top: 88rpx;
  margin-bottom: 120rpx;
}

.message-list {
  padding: 20rpx;
}

.message-item {
  display: flex;
  margin-bottom: 32rpx;
  align-items: flex-start;
}

.message-item.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 72rpx;
  height: 72rpx;
  border-radius: 36rpx;
  background-color: #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  margin: 0 16rpx;
  flex-shrink: 0;
}

.message-bubble {
  max-width: 500rpx;
  padding: 24rpx;
  border-radius: 16rpx;
  position: relative;
}

.message-item.user .message-bubble {
  background-color: #007aff;
  color: white;
}

.message-item.assistant .message-bubble {
  background-color: white;
  color: #333;
  border: 1rpx solid #e5e5e5;
}

.message-bubble.typing {
  background-color: #f0f0f0;
}

.message-text {
  font-size: 28rpx;
  line-height: 1.4;
  word-wrap: break-word;
}

.typing-text {
  font-size: 28rpx;
  color: #999;
}

/* 输入区域 */
.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  border-top: 1rpx solid #e5e5e5;
  padding: 20rpx;
  z-index: 100;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.message-input {
  flex: 1;
  height: 72rpx;
  padding: 0 24rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 36rpx;
  font-size: 28rpx;
  background-color: #f8f8f8;
}

.send-btn {
  width: 120rpx;
  height: 72rpx;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 36rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn.disabled {
  background-color: #ccc;
  color: #999;
}
</style>
